﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

using S9Engine;

public partial class Ajax : Parser
{
    private long _id;
    private long _did;
    private string _name;
    private bool _response;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            _parser.SetCurrentDir("~/html/ajax");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            _response = true;
            _id = 0; _did = 0;

            if ((Request["type"] != null && !"login,language".Contains(GetRequest("type")) && !CheckLogin()))
            {
                AjaxResponse("redirect=login.aspx");
                return;
            }
            
            LoadFile("ajax.html", true);

            if (Request["id"] != null) _id = long.Parse(Request["id"]);
            if (Request["did"] != null) _did = long.Parse(Request["did"]);
            if (Request["type"] != null) _name = Request["type"];

            string type = GetRequest("type");
            string action = GetRequest("action");
                        
            if (string.IsNullOrEmpty(type)) throw new Exception("Error:Invalid ajax request");

            switch (type)
            {
                case "login": Login(); break;
                case "logout": LogOut(); break;
                case "users":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewUser(); break;
                            case "edit": EditUser(); break;
                            case "check": CheckUserExistence(); break;
                            case "delete": DeleteUser(); break;
                            case "classify": SaveClassification(); break;
                        }
                        break;
                    }
                case "news":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewNews(); break;
                            case "edit": EditNews(); break;
                            case "delete": DeleteNews(); break;
                        }
                        break;
                    }
                case "category":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewCategory(); break;
                            case "edit": EditCategory(); break;
                            case "delete": DeleteCategory(); break;
                        }
                        break;
                    }
                case "email": {
                    if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                    switch (action)
                    {
                        case "addnew": AddNewEmail(); break;
                        case "edit": EditEmail(); break;
                        case "delete": DeleteEmail(); break;
                        case "sendmailsale": SendMailSale(); break;
                    }
                    break;
                }
                case "product":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewProduct(); break;
                            case "edit": EditProduct(); break;
                            case "delete": DeleteProduct(); break;
                        }
                        break;
                    }
                case "order":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "confirm": ConfirmOrder(); break;
                            case "delete": DeleteOrder(); break;
                        }
                        break;
                    }
                case "language": ChangeLanguage(); break;
                case "setting":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "save": SaveSetting(); break;
                            case "delete": DeleteSetting(); break;
                        }
                        break;
                    }
                case "advertises":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewAdvertise(); break;
                            case "edit": EditAdvertise(); break;
                            case "delete": DeleteAdvertise(); break;
                        }
                        break;
                    }
                case "positions":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");

                        switch (action)
                        {
                            case "addnew": AddNewPosition(); break;
                            case "edit": EditPosition(); break;
                            case "delete": DeletePosition(); break;
                        }
                        break;
                    }
                case "layout":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Error:Invalid ajax request");
                        SaveLayout(action);
                        break;
                    }
                case "file":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "delete": DeleteFile(); break;
                        }
                        break;
                    }
                case "term":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "addnew": AddTerm(); break;
                            case "edit": EditTerm(); break;
                            case "delete": DeleteTerm(); break;
                        }
                        break;
                    }
                case "gallery":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "addnew": AddNewGallery(); break;
                            case "edit": EditGallery(); break;
                            case "delete": DeleteGallery(); break;
                        }
                        break;
                    }
                case "promotion":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "addnew": AddNewPromotion(); break;
                            case "edit": EditPromotion(); break;
                            case "delete": DeletePromotion(); break;
                        }
                        break;
                    }
                case "shipping":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {
                            case "addnew": AddNewShipping(); break;
                            case "edit": EditShipping(); break;
                            case "delete": DeleteShipping(); break;
                        }
                        break;
                    }
                case "regissale":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");

                        switch (action)
                        {                                                       
                            case "delete": DeleteRegisSale(); break;
                        }
                        break;
                    }
                case "roomgallery":
                    {
                        if (string.IsNullOrEmpty(action)) throw new Exception("Missing action parameter!");
                        switch (action)
                        {
                            case "addnew": AddRoomGallery(); break;
                            case "edit": EditRoomGallery(); break;
                            case "delete": DeleteSetting(); break;
                            case "addNewDetails": AddNewDetails(); break;
                            case "genjsfile": GenJsFile(); break;
                            //case "selectType": SelectType("room_type.html"); break;
                        }
                        break;
                    }
                
                default: throw new Exception("Error:Invalid ajax request");
            }
        }
        catch (Exception ex)
        {
            _response = true;
            WriteError(ex);
        }
        finally
        {
            if (_response)
            {
                _parser.Parse("Main");
                _parser.Out("Main");
            }
        }
    }

    #region Other Functions

    private string GetRequest(string key)
    {
        return Request[key] == null ? string.Empty : Server.UrlDecode(Request[key].ToString());
    }

    private string GetRequest(string key, string defaultValue)
    {
        return Request[key] == null || string.IsNullOrEmpty(Request[key]) ? defaultValue : Server.UrlDecode(Request[key].ToString());
    }

    private void ChangeLanguage()
    {
        try
        {
            string langCode = GetRequest("code");

            if (string.IsNullOrEmpty(langCode))
            {
                AjaxResponse("Error");
            }
            else
            {
                Session["Language"] = langCode.ToUpper();
                _currentLanguage = Session["Language"].ToString();
                AjaxResponse("OK");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void SaveLayout(string type)
    {
        try
        {
            long key = 0;
            long order = 0;
            long value = 0;
            bool exist = true;

            MatchCollection mc = Regex.Matches(Request.Form["selectObject"].ToString(), "p-(\\d+) o-(\\d+) od-(\\d+)");
            List<Relations> relations = _DR.Relations.Where(r => r.Type.Equals(type) && r.LanguageCode.Equals(_currentLanguage)).ToList();
            Relations relation = null;

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            _DR.SaveChanges();

            foreach (Match m in mc)
            {
                value = long.Parse(m.Groups[1].Value.ToString());
                key = long.Parse(m.Groups[2].Value.ToString());
                order = long.Parse(m.Groups[3].Value.ToString());

                relation = _DR.Relations.Where(r => r.Type.Equals(type) & r.Child.Equals(key)).FirstOrDefault();

                if (relation == null)
                {
                    exist = false;
                    relation = new Relations();
                }

                relation.Type = type;
                relation.Child = key;
                relation.Parent = value;
                relation.Order = order;
                relation.LanguageCode = _currentLanguage;

                if (!exist) _DR.AddToRelations(relation);

                exist = true;
            }

            mc = null;
            relations = null;
            relation = null;

            _DR.SaveChanges();

            AjaxResponse("OK:Save layout done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteFile()
    {
        string fileURL = GetRequest("fileURL");
        string filePath = Request.MapPath(fileURL.Replace("~/..", _webcmsPath));

        if (System.IO.File.Exists(filePath))
        {
            System.IO.File.Delete(filePath);
            AjaxResponse("OK: Delete file done!");
        }
        else
        {
            throw new Exception("Invalid file path");
        }
    }  

    private void AjaxResponse(string value)
    {
        _parser.Assign("errorCode", value);
    }

    #endregion Other Functions

	#region Setting

    private void SaveSetting()
    {
        string mode = GetRequest("mode");
        string settingType = string.Empty;

        switch (mode)
        {
            case "setting":
                {
                    settingType = "setting-" + _currentLanguage;
                    break;
                }
            case "support":
                {
                    settingType = "support";
                    break;
                }
            default: throw new Exception("Invalid setting mode!");
        }

        NameValueCollection nvc = Request.Form;                

        if (nvc.Count == 0)
        {
            AjaxResponse("Error: Save setting fail!");
        }
        else
        {
            Meta meta = null;
            string key = string.Empty;

            for (int i = 0; i < nvc.Count; i++)
            {
                key = nvc.Keys[i].ToString().ToLower();
                meta = _DR.Meta.Where(m => m.Type.Equals(settingType) && m.Key.ToLower().Equals(key)).FirstOrDefault();

                if (meta == null)
                {
                    meta = new Meta();

                    meta.Type = settingType;
                    meta.Object = 0;
                    meta.Key = nvc.Keys[i];
                    meta.Value = nvc.GetValues(i)[0];
                    meta.LanguageCode = _currentLanguage;

                    _DR.AddToMeta(meta);
                }
                else
                {
                    meta.Value = nvc.GetValues(i)[0];
                }
            }

            meta = null;

            AjaxResponse("OK: Save setting done!");
        }

        _DR.SaveChanges();

        nvc = null;
    }

    private void AddNewDetails() {
        //string galleryType = GetRequest("type_gallery");
        //string galleryName = GetRequest("galleryName");
        //string galleryGroup = GetRequest("galleryGroup");
        //string galleryImage = GetRequest("galleryImage");
        string mode = Request["mode"] ?? "";
        string to = GetRequest("spot_to");
        string x1 = GetRequest("spot_x"), y1 = GetRequest("spot_y"), x2 = GetRequest("spot_X1"), y2 = GetRequest("spot_Y1");
        string info = GetRequest("spot_info"), content = GetRequest("spot_content"), link = GetRequest("spot_link");

        //long roomID = 0;
        
        //roomID = AddNewRoomGallery(galleryGroup, galleryName, galleryImage, true);        
        //if (roomID == "") { AjaxResponse("Error: Invalid gallery!"); return; }
        //switch (galleryType)
        //{
            AddNewRoomDetails(0, "spot", "x: " + x1 + ", y: " + y1, "", content, to, true);
            //case "tooltip": AddNewRoomDetails(_id, "tooltip", "x1: " + x1 + ", y1: " + y1 + ", x2: " + x2 + ", y2:" + y2, "", content, "", true); break;
            //case "area": AddNewRoomDetails(_id, "area", "x: " + x1 + ", y:" + y1, "", content, "", true); break;
            //case "info": AddNewRoomDetails(_id, "info", "x: " + x1 + ", y:" + y1 + ", width: " + x2 + ", height:" + y2, info, content, link, true); break;
        //}

        AjaxResponse("OK: Save setting done!");
        _DR.SaveChanges();  
    }
    private void GenJsFile() { 
        //GalleryRoom
        //GalleryRoom();
        //var list = LoadAllGallery().ToList();
        StringBuilder sb = new StringBuilder();
        sb.Append("var imagesCollection = {\"image\": [");
        
        string end = "}";
        sb.Append("{");
        sb.Append("\"id\": " + 0);
        sb.Append(", \"group\": \"" + "vietnam_map\"");
        sb.Append(", \"name\": \"" + "vietnam_map\"");
        sb.Append(", \"src\": \"" + _webcmsPath + "/uploads/image/vietnam.png\",");
        var dtSpot = (from r in _DR.RoomDetails.Where(r1 => r1.LanguageCode.Equals(_currentLanguage) && r1.Object.Equals(0))
                      select new
                      {
                          ID = r.ID,
                          Link = r.Link,
                          Content = r.Content,
                          Coordinate = r.Coordinates
                      }).DistinctBy(r1 => r1.ID).ToList();
        if (dtSpot.Count > 0)
        {
            sb.Append("\"spot\": [");
            for (int j = 0; j < dtSpot.Count; ++j)
            {
                string endDigit = (j == dtSpot.Count - 1) ? "" : ",";
                sb.Append("{to: \"" + dtSpot[j].Link + "\"," + dtSpot[j].Coordinate + ", info: \"" + dtSpot[j].Content + "\"}" + endDigit);
            }
            sb.Append("],");
        }
        sb.Append("\"info\": [");
        sb.Append("]");
        sb.Append(end);
        //}
        sb.Append("]};");
        string str = sb.ToString();
        File.WriteAllText(Server.MapPath("js/roomgallery.js"), str);
        AjaxResponse("OK: Save change done!");
    }

    private void DeleteSetting()
    {
        if (_id == 0) throw new Exception("Invalid setting ID!");

        Meta meta = _DR.Meta.Where(m => m.ID.Equals(_id)).FirstOrDefault();

        if (meta == null) throw new Exception("Invalid setting ID!");

        _DR.DeleteObject(meta);

        _DR.SaveChanges();

        meta = null;

        AjaxResponse("OK: Delete setting done!");
    }
    static long roomGalleryID = 0;
    private void AddRoomGallery()
    {
        string galleryType = GetRequest("type_gallery");
        string mode = Request["mode"]??"";
        string spotLink = GetRequest("spot_to");
        string x1 = GetRequest("spot_x"), y1 = GetRequest("spot_y");
        string info = GetRequest(galleryType + "spot_info"), content = GetRequest("spot_content"), link = GetRequest(galleryType + "spot_link");
        
        long roomID = 0;
        
        AddNewRoomDetails(roomGalleryID, "spot", "x: " + x1 + ", y: " + y1, "", content, spotLink, true);
        roomGalleryID = string.IsNullOrEmpty(mode) ? roomID : roomGalleryID;
             
        
        AjaxResponse("OK: Save setting done!");
        _DR.SaveChanges();     
    }
    private void EditRoomGallery() {
        try
        {
            //if (_id == 0) throw new Exception("Invalid product ID!");

            //string galleryType = GetRequest("type_gallery");
            //string galleryName = GetRequest("galleryName");
            //string galleryGroup = GetRequest("galleryGroup");
            //string galleryImage = GetRequest("galleryImage");
            string roomgalleryid = GetRequest("roomgalleryid");
            //string roomgalleryobject = GetRequest("spot_to");
            string spotLink = GetRequest("spot_to");
            string coordiante="";
            string x1 = GetRequest("spot_x"), y1 = GetRequest("spot_y"), x2 = GetRequest("spot_X1"), y2 = GetRequest("spot_Y1");
            string info = GetRequest("spot_info"), content = GetRequest("spot_content"), link = GetRequest("spot_link");            

            //if (IsNullValues(galleryName, galleryImage))
            //{
                //throw new Exception("Invalid product data!");
            //}

            //else
            //{
                //bool editOK = EditRoom(_id, galleryGroup, galleryName, galleryImage, true);

                //if (!editOK) throw new Exception("Invalid gallery ID!");
                //Exception editProductFailException = new Exception("Cannot edit gallery!");                                

                _DR.SaveChanges();
                //switch (galleryType) {
                    coordiante = "x: "+x1+", y: "+y1;
                    //case "tooltip": coordiante= "x1: "+x1+", y1: "+y1+", x2: "+x2+", y2:"+y2; break;
                    //case "area": coordiante="x: "+x1+", y:"+y1; break;
                    //case "info": coordiante="x: "+x1+", y:"+y1+", width: "+x2+", height:"+y2; break;
                //}
                if (_did != 0) {
                    UpdateRoomDetails(_did, _id, "spot", coordiante, info, content, spotLink, true);
                    //else { UpdateRoomDetails(_did, _id, galleryType, coordiante, info, content, link, true); }
                }
                                
                //editProductFailException = null;

                AjaxResponse("OK: Edit product done!");
            //}
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
    private void SelectType(string htmlFile) {
        LoadFile(htmlFile, true);
        if (_id == 0) throw new Exception("Invalid  ID!");
        string galleryType = Request["gType"]??"spot";
        List<RoomDetails> roomDetails = _DR.RoomDetails.Where(r => r.Object.Equals(_id) && r.Type.Equals(galleryType) && r.LanguageCode.Equals(_currentLanguage)).ToList();
        foreach (var dt in roomDetails)
        {
            _parser.Assign("roomDetailsID", dt.ID.ToString());
            _parser.Assign("roomDetailsObject", dt.Object.ToString());
            _parser.Assign("roomDetailsType", dt.Type);
            _parser.Assign("roomDetailsValue", dt.Value);
            _parser.Assign("roomDetailsContent", dt.Content);
            _parser.Assign("roomDetailsLink", dt.Link);
            _parser.Assign("roomCoordinates", dt.Coordinates);
            string[] tmp = dt.Coordinates.Split(',');
            if (tmp.Length < 3)
            {
                _parser.Assign("x1", Fiter(tmp[0]));
                _parser.Assign("y1", Fiter(tmp[1]));
            }
            else
            {
                _parser.Assign("x1", Fiter(tmp[0]));
                _parser.Assign("y1", Fiter(tmp[1]));
                _parser.Assign("x2", Fiter(tmp[2]));
                _parser.Assign("y2", Fiter(tmp[3]));
            }
            _parser.Parse("Main.Content.EditForm.Type.TypeItem");
        }
        _parser.Parse("Main.Content.EditForm.Type");
        _parser.Parse("Main.Content.EditForm");
        _parser.Parse("Main.Content");
    }
    #endregion

    #region Login & Logout

    private void Login()
    {
        try
        {
            string username = GetRequest("username");
            string password = GetRequest("password");
            string language = GetRequest("languageSelect");

            var users = _DR.Users.Where(t => t.Username.Equals(username) || t.Password.Equals(password)).ToList();

            if (users.Count == 0)
            {
                AjaxResponse("invalidAll");
            }
            else if (users.Where(t => t.Username.Equals(username)).Count() == 0)
            {
                AjaxResponse("invalidUsername");
            }
            else if (users.Where(t => t.Password.Equals(password)).Count() == 0)
            {
                AjaxResponse("invalidPassword");
            }
            else
            {
                Session["IsLogged"] = "1";
                Session["FullName"] = _DR.Users.Where(t => t.Username.Equals(username) && t.Password.Equals(password)).Select(t => t.Fullname).FirstOrDefault();
                Session["UserType"] = _DR.Users.Where(t => t.Username.Equals(username) && t.Password.Equals(password)).Select(t => t.Type).FirstOrDefault();

                Session["Language"] = string.IsNullOrEmpty(language) ? _parser.GetConfig("DefaultLanguage", "VN") : language;
                _currentLanguage = language;
                AjaxResponse("redirect=" + _parser.GetConfig("DefaultPage", "Category.aspx"));
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LogOut()
    {
        try
        {
            Session["IsLogged"] = "0";
            Session["FullName"] = string.Empty;
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    #endregion Login & Logout

    #region Users

    private void CheckUserExistence()
    {
        try
        {
            string username = GetRequest("userUserName");

            if (_DR.Users.Where(t => t.Username.Equals(username)).Count() == 0)
            {
                AjaxResponse("true");
            }
            else
            {
                AjaxResponse("false");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void AddNewUser()
    {
        try
        {
            string username = GetRequest("userUserName");
            string password = GetRequest("userPassword");
            string fullname = GetRequest("userFullName");
            string userType = GetRequest("userType");

            if (IsNullValues(username, password, fullname, userType)) throw new Exception("Error");

            Users user = new Users();

            user.Username = username;
            user.Password = password;
            user.Fullname = fullname;
            user.Type = userType;
            user.LanguageCode = _currentLanguage;

            _DR.AddToUsers(user);
            _DR.SaveChanges();

            user = null;

            AjaxResponse("OK: Add new user done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditUser()
    {
        try
        {
            if (_id == 0) throw new Exception("Invalid user ID!");

            string username = GetRequest("userUserName");
            string password = GetRequest("userPassword");
            string fullname = GetRequest("userFullName");
            string userType = GetRequest("userType");

            if (IsNullValues(username, password, fullname)) throw new Exception("Invalid user data!");

            Users user = _DR.Users.Where(t => t.ID.Equals(_id)).FirstOrDefault();

            user.Username = username;
            user.Password = password;
            user.Fullname = fullname;
            user.Type = userType;

            _DR.SaveChanges();

            user = null;

            AjaxResponse("OK: Edit user done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteUser()
    {
        try
        {
            string[] stringIDs = GetRequest("userID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Users> users = _DR.Users.WhereIn(u => u.ID, longIDs).ToList();

            foreach (Users u in users)
            {
                _DR.DeleteObject(u);
            }

            List<Permission> permissions = _DR.Permission.WhereIn(p => p.User, longIDs).ToList();

            foreach (Permission p in permissions)
            {
                _DR.DeleteObject(p);
            }

            _DR.SaveChanges();

            users = null;
            permissions = null;

            AjaxResponse("OK: Delete user done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void SaveClassification()
    {
        try
        {
            if (_id == 0) throw new Exception("Invalid user id!");

            bool exist = true;

            Permission permission = _DR.Permission.Where(p => p.User.Equals(_id) && p.Type.Equals("function")).FirstOrDefault();

            if (permission == null)
            {
                permission = new Permission();
                exist = false;
            } 
            
            permission.User = _id;
            permission.Type = "function";
            permission.Read = GetRequest("viewFunction");
            permission.Write = GetRequest("editFunction");

            if (!exist) _DR.AddToPermission(permission);

            exist = true;

            permission = _DR.Permission.Where(p => p.User.Equals(_id) && p.Type.Equals("category")).FirstOrDefault();

            if (permission == null)
            {
                permission = new Permission();
                exist = false;
            } 

            permission.User = _id;
            permission.Type = "category";
            permission.Read = GetRequest("viewCategory");
            permission.Write = GetRequest("editCategory");

            if (!exist) _DR.AddToPermission(permission);

            _DR.SaveChanges();

            permission = null;

            AjaxResponse("OK: Save user classification done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
        
    #endregion Users

    #region News

    private void AddNewNews()
    {
        try
        {
            string newsTitle = GetRequest("newsTitle");
            string newsExcerpt = GetRequest("newsExcerpt");
            string newsImage = GetRequest("newsImage");            
            string newsDate = GetRequest("newsDate");                    
            string newsOrder = GetRequest("newsOrder");
            string newsContent = GetRequest("newsContent");
            string newsHome = GetRequest("newsHome");
            string[] newsCategories = GetRequest("selectCategory").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (IsNullValues(newsTitle, newsDate, newsCategories)) throw new Exception("Error");

            Posts post = new Posts();

            post.Content = newsContent;
            post.Date = Convert.ToDateTime(Convert.ToDateTime(newsDate).ToShortDateString());
            post.Excerpt = newsExcerpt;
            post.LanguageCode = _currentLanguage;
            post.MIMEType = "html";
            post.Order = long.Parse(string.IsNullOrEmpty(newsOrder) ? "0" : newsOrder);
            post.Parent = 0;
            post.Password = string.Empty;
            post.Status = "Published";
            post.Title = newsTitle;
            post.Type = "news";

            _DR.AddToPosts(post);
            _DR.SaveChanges();

            Meta meta = new Meta();

            meta.Object = post.ID;
            meta.Type = "news";
            meta.Key = "NewsImage";
            meta.Value = newsImage;
            meta.LanguageCode = _currentLanguage;

            _DR.AddToMeta(meta);
            AddNewMeta(post.ID, "news", "NewsHome", (newsHome=="true").ToString(), false);

            Relations relation = null;

            foreach (string s in newsCategories)
            {
                relation = new Relations();

                relation.Child = post.ID;
                relation.Parent = long.Parse(s);
                relation.Type = "news-category";
                relation.Order = long.Parse(newsOrder);
                relation.LanguageCode = _currentLanguage;

                _DR.AddToRelations(relation);
            }

            _DR.SaveChanges();

            relation = null;
            post = null;

            AjaxResponse("OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditNews()
    {
        try
        {
            if (_id == 0) throw new Exception("Error");

            string newsTitle = GetRequest("newsTitle");
            string newsExcerpt = GetRequest("newsExcerpt");
            string newsDate = GetRequest("newsDate");
            string newsImage = GetRequest("newsImage");
            string newsAuthor = GetRequest("newsAuthor");
            string newsDocument = GetRequest("newsDocument");
            string newsHome = GetRequest("newsHome");
            string newsImageThubnail = GetRequest("newsImageThumbnail");
            string newsOrder = GetRequest("newsOrder");
            string newsContent = GetRequest("newsContent");
            string[] newsCategories = GetRequest("selectCategory").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (IsNullValues(newsTitle, newsDate, newsCategories, _id)) throw new Exception("Error");

            Posts post = _DR.Posts.Where(p => p.Type.Equals("news") && p.ID.Equals(_id)).FirstOrDefault();

            post.Content = newsContent;
            post.Date = Convert.ToDateTime(Convert.ToDateTime(newsDate).ToShortDateString());
            post.Excerpt = newsExcerpt;
            post.LanguageCode = _currentLanguage;
            post.MIMEType = "html";
            post.Order = long.Parse(string.IsNullOrEmpty(newsOrder) ? "0" : newsOrder);
            post.Parent = 0;
            post.Password = string.Empty;
            post.Status = "Published";
            post.Title = newsTitle;
            post.Type = "news";

            Meta newsImageMeta = _DR.Meta.Where(m => m.Object.Equals(_id) && m.Type.Equals("news") && m.Key.Equals("NewsImage")).FirstOrDefault();

            if (newsImageMeta != null) newsImageMeta.Value = newsImage;

            Meta newsAuthorMeta = _DR.Meta.Where(m => m.Object.Equals(_id) && m.Type.Equals("news") && m.Key.Equals("Author")).FirstOrDefault();

            if (newsAuthorMeta != null) newsAuthorMeta.Value = newsAuthor;
            Meta newsDocumentMeta = _DR.Meta.Where(m => m.Object.Equals(_id) && m.Type.Equals("news") && m.Key.Equals("Document")).FirstOrDefault();

            if (newsDocumentMeta != null) newsDocumentMeta.Value = newsDocument;

            Meta newsImageThubnailMeta = _DR.Meta.Where(m => m.Object.Equals(_id) && m.Type.Equals("news") && m.Key.Equals("NewsImageThumbnail")).FirstOrDefault();

            if (newsImageThubnailMeta != null) newsImageThubnailMeta.Value = newsImageThubnail;

            if (!EditMetaByObject(_id, "news", "NewsHome", (newsHome == "true").ToString(), false)) {
                AddNewMeta(_id, "news", "NewsHome", (newsHome == "true").ToString(), false);
            }


            List<Relations> relations = _DR.Relations.Where(r => r.Type.Equals("news-category") && r.Child.Equals(_id)).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            _DR.SaveChanges();

            Relations relation = null;

            foreach (string s in newsCategories)
            {
                relation = new Relations();

                relation.Child = post.ID;
                relation.Parent = long.Parse(s);
                relation.Type = "news-category";
                relation.Order = long.Parse(newsOrder);
                relation.LanguageCode = _currentLanguage;
                _DR.AddToRelations(relation);
            }

            _DR.SaveChanges();

            relations = null;
            relation = null;
            post = null;
            newsImageMeta = null;
            newsImageThubnailMeta = null;
            newsAuthorMeta = null;
            newsDocumentMeta = null;

            AjaxResponse("OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteNews()
    {
        try
        {
            string[] stringIDs = GetRequest("newsID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Posts> news = _DR.Posts.WhereIn(p => p.ID, longIDs).ToList();

            foreach (Posts p in news)
            {
                _DR.DeleteObject(p);
            }

            List<Relations> relations = _DR.Relations.WhereIn(r => r.Child, longIDs).Where(r => r.Type.Equals("news-category")).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("news")).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            _DR.SaveChanges();

            news = null;
            relations = null;

            AjaxResponse("OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    #endregion News

    #region Category

    private void AddNewCategory()
    {
        try
        {
            string categoryName = GetRequest("categoryName");
            string categoryURL = GetRequest("categoryURL");
            string categoryImage = GetRequest("categoryImage");
            string categoryExcerpt = GetRequest("categoryExcerpt");
            string parentCategory = GetRequest("parentCategory");
            string categoryFilter = GetRequest("categoryFilter");

            if (IsNullValues(categoryName, categoryFilter)) throw new Exception("Error:Invalid category ID");

            Terms term = new Terms();

            term.Group=0;
            term.LanguageCode = _currentLanguage;
            term.Name = categoryName;
            term.Slug = string.Empty;

            _DR.AddToTerms(term);

            _DR.SaveChanges();

            Taxonomy taxonomy = new Taxonomy()
            {
                Description = categoryExcerpt,
                LanguageCode = _currentLanguage,
                Name = categoryFilter + "-category",
                Parent = long.Parse(parentCategory),
                Term = term.ID
            };

            _DR.AddToTaxonomy(taxonomy);

            Meta meta = new Meta();

            meta.Type = "category";
            meta.Object = term.ID;
            meta.Key = "CategoryURL";
            meta.Value = categoryURL.ToLower();
            meta.LanguageCode = _currentLanguage;

            _DR.AddToMeta(meta);

            meta = new Meta();

            meta.Type = "category";
            meta.Object = term.ID;
            meta.Key = "CategoryImage";
            meta.Value = categoryImage.ToLower();
            meta.LanguageCode = _currentLanguage;

            _DR.AddToMeta(meta);

            _DR.SaveChanges();

            term = null;
            taxonomy = null;
            meta = null;

            AjaxResponse("OK: Add new category done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditCategory()
    {
        try
        {
            if (_id == 0) throw new Exception("Invalid category ID");

            string categoryName = GetRequest("categoryName");
            string categoryURL = GetRequest("categoryURL");
            string categoryImage = GetRequest("categoryImage");
            string categoryExcerpt = GetRequest("categoryExcerpt");
            string parentCategory = GetRequest("parentCategory");

            if (IsNullValues(categoryName))
            {
                throw new Exception("Invalid category data!");
            }
            else
            {
                Terms term = _DR.Terms.Where(t => t.ID.Equals(_id)).FirstOrDefault();

                term.Name = categoryName;
                
                Taxonomy taxonomy = _DR.Taxonomy.Where(t => t.Term.Equals(_id)).FirstOrDefault();

                taxonomy.Description = categoryExcerpt;
                taxonomy.Parent = long.Parse(parentCategory);

                Meta meta = _DR.Meta.Where(m => m.Type.Equals("category") && m.Object.Equals(term.ID) && m.Key.Contains("CategoryURL")).FirstOrDefault();

                if (meta != null) meta.Value = categoryURL.ToLower();

                meta = _DR.Meta.Where(m => m.Type.Equals("category") && m.Object.Equals(term.ID) && m.Key.Contains("CategoryImage")).FirstOrDefault();

                if (meta != null) meta.Value = categoryImage.ToLower();

                _DR.SaveChanges();

                term = null;
                taxonomy = null;
                meta = null;

                AjaxResponse("OK: Edit category done!");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteCategory()
    {
        try
        {
            string[] stringIDs = GetRequest("categoryID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Terms> terms = _DR.Terms.WhereIn(t => t.ID, longIDs).ToList();

            foreach (Terms t in terms)
            {
                _DR.DeleteObject(t);
            }

            // Reset all child item's parentID
            List<Taxonomy> taxonomies = _DR.Taxonomy.WhereIn(t => t.Parent, longIDs).ToList();

            foreach (Taxonomy t in taxonomies)
            {
                t.Parent = 0;
            }

            taxonomies = _DR.Taxonomy.WhereIn(t => t.Term, longIDs).ToList();

            string termType = taxonomies[0].Name;

            foreach (Taxonomy t in taxonomies)
            {
                _DR.DeleteObject(t);
            }

            List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("category")).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            List<Relations> relations = _DR.Relations.WhereIn(r => r.Child, longIDs).Where(r => r.Type.Contains(termType)).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            relations = _DR.Relations.WhereIn(r => r.Parent, longIDs).Where(r => r.Type.Contains(termType)).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            _DR.SaveChanges();

            terms = null;
            taxonomies = null;
            metas = null;

            AjaxResponse("OK: Delete category done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
    #endregion Category
    
    private void AddNewEmail() {
        try
        {
            string categoryName = GetRequest("categoryName");
            string filePath = Server.MapPath("uploads/mail/"+categoryName.Replace(".txt", "")+".txt");
            string categoryExcerpt = GetRequest("categoryExcerpt");            
            string categoryFilter = GetRequest("categoryFilter");
            if (IsNullValues(categoryName, categoryFilter)) throw new Exception("Error:Invalid category ID");
            
            File.WriteAllText(filePath, categoryExcerpt, Encoding.UTF8);

            AjaxResponse("OK: Add new category done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
    private void EditEmail() {
        try
        {
            if (_name == "") throw new Exception("Invalid category file name");

            string categoryName = GetRequest("categoryName");            
            string categoryExcerpt = GetRequest("categoryExcerpt");            

            if (IsNullValues(categoryName))
            {
                throw new Exception("Invalid category data!");
            }
            else
            {
                if (categoryName == _name)
                { 
                    File.WriteAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"), categoryExcerpt, Encoding.UTF8); 
                }
                else
                {
                    //Delete
                    //File.Delete(Server.MapPath("uploads/mail/" + _name));   
                    File.Delete(Server.MapPath("uploads/mail/" + _name));
                    //Creat File
                    File.WriteAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"), categoryExcerpt, Encoding.UTF8);                    
                }
                AjaxResponse("OK: Edit category done!");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void SendMailSale()
    {
        try
        {
            if (_name == "") throw new Exception("Invalid category file name");

            string categoryName = GetRequest("categoryName");
            string categoryExcerpt = GetRequest("categoryExcerpt");

            if (IsNullValues(categoryName))
            {
                throw new Exception("Invalid category data!");
            }
            else
            {
                List<string> users = _DR.Users.Where(u => u.Type.Equals("Customer")).Select(u=>u.Fullname).ToList();
                string subject1 = _parser.GetConfig("ConfirmSubject", "Confirm") + " " + DateTime.Now.ToShortDateString();
                string name = _parser.GetConfig("NameEmail", "E-Commerces");
                if (categoryName == _name)
                {
                    File.WriteAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"), categoryExcerpt, Encoding.UTF8);
                    string fromEmail = _parser.GetConfig("ConfirmEmail", "gnat0309@gmail.com");
                    string mailBody = File.ReadAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"));
                    string mainBodyDeCode = HttpUtility.HtmlDecode(mailBody);
                    //Send mail
                    foreach (string str in users) {
                        //SendEmail("gnat0309@gmail.com", "145313211", "Ecom", "nktang.a4@gmail.com", "nktang", "subject", mailBody);                
                        SendEmail("gnat0309@gmail.com", "145313211", name, str, str.ToString(), subject1, mainBodyDeCode);                                                
                    }
                }
                    
                else
                {
                    //Delete
                    //File.Delete(Server.MapPath("uploads/mail/" + _name));   
                    File.Delete(Server.MapPath("uploads/mail/" + _name));
                    //Creat File
                    File.WriteAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"), categoryExcerpt, Encoding.UTF8);
                    string fromEmail = _parser.GetConfig("ConfirmEmail", "gnat0309@gmail.com");
                    string mailBody = File.ReadAllText(Server.MapPath("uploads/mail/" + categoryName.Replace(".txt", "") + ".txt"));
                    string mainBodyDeCode = HttpUtility.HtmlDecode(mailBody);
                    foreach (string str in users)
                    {
                        //SendEmail("gnat0309@gmail.com", "145313211", "Ecom", "nktang.a4@gmail.com", "nktang", "subject", mailBody);                
                        SendEmail("gnat0309@gmail.com", "145313211", name, str, "E-Commerces", subject1, mainBodyDeCode);                        
                    }                    
                }                
                AjaxResponse("OK: Edit category done!");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteEmail()
    {
        try
        {
            File.Delete(Server.MapPath("uploads/mail/" + _name));
        }
        catch (Exception ex) { }
    }

    #region Product

    private void AddNewProduct()
    {
        try
        {
            string productName = GetRequest("productName");
            string productCode = GetRequest("productCode");      
            string productExcerpt = GetRequest("productExcerpt");
            string productContent = GetRequest("productContent");           
            string productImage = GetRequest("productImage");
            string productImageDetails = GetRequest("productImageDetails");
           
            string productDate = GetRequest("productDate");
            string productQuantity = GetRequest("productQuantity", "1");
            string productAlcohol = GetRequest("productAlcohol");
            string productBeer = GetRequest("productBeer");

            string[] productCategories = GetRequest("selectCategory").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (IsNullValues(productName, productDate, productExcerpt, productContent, productQuantity, productCategories))
            {
                throw new Exception("Invalid product data!");
            }
            else
            {
                long productID = AddNewProduct(productDate, productExcerpt, productName,"0", productQuantity, productImage, productContent, true, "");

                Exception newProductException = new Exception("Cannot add new product!");

                if (productID == 0) throw newProductException;

                AddNewMeta(productID, "product", "Code", productCode, false);                
                AddNewMeta(productID, "product", "HotAlcohol", (productAlcohol == "true").ToString(), false);
                AddNewMeta(productID, "product", "HotBeer", (productBeer == "true").ToString(), false);
                AddNewMeta(productID, "product", "ImageDetail", productImageDetails, false);

                foreach (string s in productCategories)
                {
                    AddNewRelation("product-category", productID, long.Parse(s), 0, false);
                }

                _DR.SaveChanges();

                newProductException = null;

                AjaxResponse("OK: Add new product done!");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditProduct()
    {
        try
        {
            if (_id == 0) throw new Exception("Invalid product ID!");

                 

            string productName = GetRequest("productName");
            string productCode = GetRequest("productCode");
            string productExcerpt = GetRequest("productExcerpt");
            string productContent = GetRequest("productContent");
            string productImage = GetRequest("productImage");
            string productImageDetails = GetRequest("productImageDetails");
            string productDate = GetRequest("productDate");
            string productQuantity = GetRequest("productQuantity", "1");
            string productAlcohol = GetRequest("productAlcohol");
            string productBeer = GetRequest("productBeer");

            string[] productCategories = GetRequest("selectCategory").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);            

            if (IsNullValues(productName, productDate, productQuantity, productCategories))
            {
                throw new Exception("Invalid product data!");
            }
                
            else
            {
                bool editOK = EditProduct(_id, productDate, productExcerpt, productName, "0", productQuantity, productImage, productContent, false, "");

                if (!editOK) throw new Exception("Invalid product ID!");

                Exception editProductFailException = new Exception("Cannot edit product!");

                if (!EditMetaByObject(_id, "product", "Code", productCode, false)) throw editProductFailException;
                if (!EditMetaByObject(_id, "product", "HotAlcohol", (productAlcohol == "true").ToString(), false)) throw editProductFailException;
                if (!EditMetaByObject(_id, "product", "HotBeer", (productBeer == "true").ToString(), false)) throw editProductFailException;
                if (!EditMetaByObject(_id, "product", "ImageDetail", productImageDetails, false)){
                    AddNewMeta(_id, "product", "ImageDetail", productImageDetails, false);
                }                
                
                List<Relations> relations = _DR.Relations.Where(r => r.Type.Equals("product-category") && r.Child.Equals(_id)).ToList();

                foreach (Relations r in relations)
                {
                    _DR.DeleteObject(r);
                }

                Relations relation = null;

                foreach (string s in productCategories)
                {
                    relation = new Relations();

                    relation.Child = _id;
                    relation.Parent = long.Parse(s);
                    relation.Type = "product-category";
                    relation.Order = 0;
                    relation.LanguageCode = _currentLanguage;

                    _DR.AddToRelations(relation);
                }

                _DR.SaveChanges();

                relations = null;
                relation = null;
                editProductFailException = null;

                AjaxResponse("OK: Edit product done!");
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteProduct()
    {
        try
        {
            string[] stringIDs = GetRequest("productID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Products> products = _DR.Products.WhereIn(p => p.ID, longIDs).ToList();

            foreach (Products p in products)
            {
                _DR.DeleteObject(p);
            }

            List<Relations> relations = _DR.Relations.WhereIn(r => r.Child, longIDs).Where(r => r.Type.Equals("product-category")).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("product")).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            _DR.SaveChanges();

            metas = null;
            products = null;
            relations = null;

            AjaxResponse("OK: Delete product done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    #endregion Product

    #region Order

    private void DeleteOrder()
    {
        try
        {
            string[] stringIDs = GetRequest("orderID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Orders> orders = _DR.Orders.WhereIn(p => p.ID, longIDs).ToList();

            foreach (Orders p in orders)
            {
                _DR.DeleteObject(p);
            }

            List<Relations> relations = _DR.Relations.WhereIn(r => r.Child, longIDs).Where(r => r.Type.Equals("order-product")).ToList();

            foreach (Relations r in relations)
            {
                _DR.DeleteObject(r);
            }

            List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("order")).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            _DR.SaveChanges();

            metas = null;
            orders = null;
            relations = null;

            AjaxResponse("OK: Delete product done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void ConfirmOrder()
    {
        try {
            
        }
        catch (Exception ex) { WriteError(ex);}
    }
    
    #endregion

    #region Advertise

    private void AddNewAdvertise()
    {
        try
        {
            string advertiseName = GetRequest("advertiseName");
            string advertiseDescription = GetRequest("advertiseDescription");
            string advertiseContent = GetRequest("advertiseContent");

            if (IsNullValues(advertiseContent, advertiseName)) throw new Exception("Invalid advertise data!");

            Advertises advertise = new Advertises();

            advertise.Name = advertiseName;
            advertise.Description = advertiseDescription;
            advertise.Content = advertiseContent;
            advertise.LanguageCode = _currentLanguage;

            _DR.AddToAdvertises(advertise);

            _DR.SaveChanges();

            AjaxResponse("OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditAdvertise()
    {
        try
        {
            if (_id == 0) throw new Exception("Error:Invalid advertise ID");

            string advertiseName = GetRequest("advertiseName");
            string advertiseDescription = GetRequest("advertiseDescription");
            string advertiseContent = GetRequest("advertiseContent");

            if (IsNullValues(advertiseContent, advertiseName)) throw new Exception("Error:Invalid advertise data");

            Advertises advertise = _DR.Advertises.Where(a => a.ID.Equals(_id)).FirstOrDefault();

            advertise.Name = advertiseName;
            advertise.Description = advertiseDescription;
            advertise.Content = advertiseContent;

            _DR.SaveChanges();

            AjaxResponse("OK:Edit advertise OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteAdvertise()
    {
        try
        {
            string[] stringIDs = GetRequest("advertiseID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Advertises> advertises = _DR.Advertises.WhereIn(a => a.ID, longIDs).ToList();

            foreach (Advertises a in advertises)
            {
                _DR.DeleteObject(a);
            }

            if (advertises != null) _DR.SaveChanges();

            advertises = null;
            
            AjaxResponse("OK:Delete advertise OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    #endregion

    #region Position

    private void AddNewPosition()
    {
        try
        {
            string positionName = GetRequest("positionName");
            string positionCode = GetRequest("positionCode");
            string positionDescription = GetRequest("positionDescription");
            string positionContent = GetRequest("positionContent");

            if (IsNullValues(positionContent, positionCode, positionName)) throw new Exception("Invalid position data!");

            Positions position = new Positions();

            position.Name = positionName;
            position.Code = positionCode;
            position.Description = positionDescription;
            position.LanguageCode = _currentLanguage;

            _DR.AddToPositions(position);

            _DR.SaveChanges();

            AjaxResponse("OK: Add new position done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void EditPosition()
    {
        try
        {
            if (_id == 0) throw new Exception("Invalid position ID!");

            string positionName = GetRequest("positionName");
            string positionCode = GetRequest("positionCode");
            string positionDescription = GetRequest("positionDescription");
            string positionContent = GetRequest("positionContent");

            if (IsNullValues(positionContent, positionName)) throw new Exception("Invalid position data!");

            Positions position = _DR.Positions.Where(a => a.ID.Equals(_id)).FirstOrDefault();

            position.Name = positionName;
            position.Code = positionCode;
            position.Description = positionDescription;

            _DR.SaveChanges();

            AjaxResponse("OK: Edit position done!");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeletePosition()
    {
        try
        {
            string[] stringIDs = GetRequest("positionID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

            List<Positions> positions = _DR.Positions.WhereIn(a => a.ID, longIDs).ToList();

            foreach (Positions a in positions)
            {
                _DR.DeleteObject(a);
            }

            if (positions != null) _DR.SaveChanges();

            positions = null;

            AjaxResponse("OK:Delete position OK");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    #endregion

    #region Term

    private void AddTerm()
    {
        string actionType = GetRequest("actiontype");

        if (string.IsNullOrEmpty(actionType)) throw new Exception("Invalid action type!");

        string termValue = GetRequest("termValue");

        if (string.IsNullOrEmpty(termValue)) throw new Exception("Invalid term value!");

        Meta meta = new Meta();

        string type = string.Empty;

        switch (actionType)
        {
            case "style": goto default;

            default: type = "product"; meta.Object = 0; break;
        }

        meta.Type = type;
        meta.Key = actionType;
        meta.Value = termValue;
        meta.LanguageCode = _currentLanguage;

        _DR.AddToMeta(meta);

        _DR.SaveChanges();

        meta = null;

        AjaxResponse("OK: Add term done!");
    }

    private void EditTerm()
    {
        if (_id == 0) AjaxResponse("Error: Invalid term ID!");

        string actionType = GetRequest("actiontype");

        if (string.IsNullOrEmpty(actionType)) throw new Exception("Invalid action type!");

        string termValue = GetRequest("termValue");

        if (string.IsNullOrEmpty(termValue)) throw new Exception("Invalid term value!");

        Meta meta = _DR.Meta.Where(m => m.ID.Equals(_id)).FirstOrDefault();

        if (meta != null)
        {
            meta.Value = termValue;
            meta.LanguageCode = _currentLanguage;
            _DR.SaveChanges();

            AjaxResponse("OK: Edit term done!");
        }
        else
        {
            throw new Exception("Invalid term ID!");
        }

        meta = null;
    }

    private void DeleteTerm()
    {
        if (_id == 0) AjaxResponse("Error: Invalid term ID!");

        string actionType = GetRequest("actiontype");

        if (string.IsNullOrEmpty(actionType)) throw new Exception("Invalid action type!");

        Meta meta = _DR.Meta.Where(m => m.ID.Equals(_id)).FirstOrDefault();

        if (meta != null)
        {
            _DR.DeleteObject(meta);
            _DR.SaveChanges();

            AjaxResponse("OK: Remove term done!");
        }
        else
        {
            AjaxResponse("Error: Remove term fail!");
        }

        meta = null;
    }

    #endregion Term

    #region Gallery

    private void AddNewGallery()
    {
        string galleryImage = GetRequest("galleryImage");
        string galleryDescription = GetRequest("galleryDescription");
        string galleryAlbum = GetRequest("galleryAlbum");

        if (IsNullValues(galleryImage, galleryAlbum)) throw new Exception("Invalid gallery value!");

        long albumID = 0;

        if (!long.TryParse(galleryAlbum, out albumID)) throw new Exception("Invalid album ID!");

        Images image = new Images();

        image.URL = galleryImage;
        image.Description = galleryDescription;
        image.LanguageCode = _currentLanguage;

        _DR.AddToImages(image);
        _DR.SaveChanges();

        Relations relation = new Relations();

        relation.Type = "album-image";
        relation.Child = image.ID;
        relation.Parent = albumID;
        relation.Order = 0;

        _DR.AddToRelations(relation);

        _DR.SaveChanges();

        image = null;
        relation = null;

        AjaxResponse("OK: Add new image done!");
    }

    private void EditGallery()
    {
        string galleryImage = GetRequest("galleryImage");
        string galleryDescription = GetRequest("galleryDescription");
        string galleryAlbum = GetRequest("galleryAlbum");

        if (IsNullValues(galleryImage, galleryAlbum)) throw new Exception("Invalid gallery value!");

        long albumID = 0;

        if (!long.TryParse(galleryAlbum, out albumID)) throw new Exception("Invalid album ID!");

        Images image = _DR.Images.Where(i => i.ID.Equals(_id)).FirstOrDefault();

        if (image == null) throw new Exception("Invalid image ID!");

        image.URL = galleryImage;
        image.Description = galleryDescription;
        image.LanguageCode = _currentLanguage;

        _DR.SaveChanges();

        image = null;

        AjaxResponse("OK: Edit image done!");
    }

    private void DeleteGallery()
    {
        if (_id == 0) throw new Exception("Invalid image ID!");

        string galleryAlbum = GetRequest("galleryAlbum");

        long albumID = 0;

        if (!long.TryParse(galleryAlbum, out albumID)) throw new Exception("Invalid album ID!");

        Images image = _DR.Images.Where(i => i.ID.Equals(_id)).FirstOrDefault();

        if (image == null) throw new Exception("Invalid image ID!");

        _DR.DeleteObject(image);

        Relations relation = _DR.Relations.Where(r => r.Type.Equals("album-image") && r.Child.Equals(_id) && r.Parent.Equals(albumID)).FirstOrDefault();

        if (relation != null) _DR.DeleteObject(relation);

        relation = null;

        _DR.SaveChanges();

        image = null;
        relation = null;

        AjaxResponse("OK: Delete image done!");
    }

    #endregion

    #region Promotion

    private void AddNewPromotion()
    {
        string promotionCode = GetRequest("promotionCode");
        string promotionPercent = GetRequest("promotionPercent");
        string promotionExpireDate = GetRequest("promotionExpireDate");

        if (IsNullValues(promotionCode, promotionPercent, promotionExpireDate)) throw new Exception("Error:Invalid promotion data");

        if (_DR.Terms.Where(t => t.Name.Equals(promotionCode)).Count() > 0) throw new Exception("Invalid promotion code");

        Terms term = new Terms();

        term.Group = 0;
        term.LanguageCode = _currentLanguage;
        term.Name = promotionCode;
        term.Slug = string.Empty;

        _DR.AddToTerms(term);
        _DR.SaveChanges();

        Taxonomy taxonomy = new Taxonomy()
        {
            Description = string.Empty,
            LanguageCode = _currentLanguage,
            Name = "promotion",
            Parent = 0,
            Term = term.ID
        };

        _DR.AddToTaxonomy(taxonomy);

        AddNewMeta(term.ID, "promotion", "Percent", promotionPercent, false);
        AddNewMeta(term.ID, "promotion", "ExpireDate", promotionExpireDate, false);

        _DR.SaveChanges();

        term = null;
        taxonomy = null;

        AjaxResponse("OK: Add new promotion done!");
    }

    private void EditPromotion()
    {
        if (_id == 0) throw new Exception("Invalid category ID");

        string promotionCode = GetRequest("promotionCode");
        string promotionPercent = GetRequest("promotionPercent");
        string promotionExpireDate = GetRequest("promotionExpireDate");

        if (IsNullValues(promotionCode, promotionPercent, promotionExpireDate)) throw new Exception("Error:Invalid promotion data");

        Terms term = _DR.Terms.Where(t => t.ID.Equals(_id)).FirstOrDefault();

        if (term == null) throw new Exception("Invalid promotion ID");

        if (_DR.Terms.Where(t => t.Name.Equals(promotionCode) && !t.ID.Equals(_id)).Count() > 0) throw new Exception("Invalid promotion code");

        term.Name = promotionCode;

        EditMetaByObject(term.ID, "promotion", "Percent", promotionPercent, false);
        EditMetaByObject(term.ID, "promotion", "ExpireDate", promotionExpireDate, false);

        _DR.SaveChanges();

        term = null;

        AjaxResponse("OK: Edit category done!");
    }

    private void DeletePromotion()
    {
        string[] stringIDs = GetRequest("promotionID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

        List<Terms> terms = _DR.Terms.WhereIn(t => t.ID, longIDs).ToList();

        foreach (Terms t in terms)
        {
            _DR.DeleteObject(t);
        }

        List<Taxonomy> taxonomies = _DR.Taxonomy.WhereIn(t => t.Term, longIDs).ToList();

        foreach (Taxonomy t in taxonomies)
        {
            _DR.DeleteObject(t);
        }

        List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("promotion")).ToList();

        foreach (Meta m in metas)
        {
            _DR.DeleteObject(m);
        }

        _DR.SaveChanges();

        terms = null;
        taxonomies = null;
        metas = null;

        AjaxResponse("OK: Delete promotion done!");
    }

    #endregion Promotion

    #region Shipping

    private void AddNewShipping()
    {
        string shippingName = GetRequest("shippingName");
        string shippingPrice = GetRequest("shippingPrice");
        string shippingTime = GetRequest("shippingTime");

        if (IsNullValues(shippingName, shippingPrice, shippingTime)) throw new Exception("Error:Invalid shipping data");

        if (_DR.Terms.Where(t => t.Name.Equals(shippingName)).Count() > 0) throw new Exception("Invalid shipping code");

        Terms term = new Terms();

        term.Group = 0;
        term.LanguageCode = _currentLanguage;
        term.Name = shippingName;
        term.Slug = string.Empty;

        _DR.AddToTerms(term);
        _DR.SaveChanges();

        Taxonomy taxonomy = new Taxonomy()
        {
            Description = string.Empty,
            LanguageCode = _currentLanguage,
            Name = "shipping",
            Parent = 0,
            Term = term.ID
        };

        _DR.AddToTaxonomy(taxonomy);

        AddNewMeta(term.ID, "shipping", "Price", shippingPrice, false);
        AddNewMeta(term.ID, "shipping", "Time", shippingTime, false);

        _DR.SaveChanges();

        term = null;
        taxonomy = null;

        AjaxResponse("OK: Add new shipping done!");
    }

    private void EditShipping()
    {
        if (_id == 0) throw new Exception("Invalid category ID");

        string shippingName = GetRequest("shippingName");
        string shippingPrice = GetRequest("shippingPrice");
        string shippingTime = GetRequest("shippingTime");

        if (IsNullValues(shippingName, shippingPrice, shippingTime)) throw new Exception("Error:Invalid shipping data");

        Terms term = _DR.Terms.Where(t => t.ID.Equals(_id)).FirstOrDefault();

        if (term == null) throw new Exception("Invalid shipping ID");

        if (_DR.Terms.Where(t => t.Name.Equals(shippingName) && !t.ID.Equals(_id)).Count() > 0) throw new Exception("Invalid shipping code");

        term.Name = shippingName;

        EditMetaByObject(term.ID, "shipping", "Price", shippingPrice, false);
        EditMetaByObject(term.ID, "shipping", "Time", shippingTime, false);

        _DR.SaveChanges();

        term = null;

        AjaxResponse("OK: Edit category done!");
    }

    private void DeleteShipping()
    {
        string[] stringIDs = GetRequest("shippingID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

        List<Terms> terms = _DR.Terms.WhereIn(t => t.ID, longIDs).ToList();

        foreach (Terms t in terms)
        {
            _DR.DeleteObject(t);
        }

        List<Taxonomy> taxonomies = _DR.Taxonomy.WhereIn(t => t.Term, longIDs).ToList();

        foreach (Taxonomy t in taxonomies)
        {
            _DR.DeleteObject(t);
        }

        List<Meta> metas = _DR.Meta.WhereIn(m => m.Object, longIDs).Where(m => m.Type.Equals("shipping")).ToList();

        foreach (Meta m in metas)
        {
            _DR.DeleteObject(m);
        }

        _DR.SaveChanges();

        terms = null;
        taxonomies = null;
        metas = null;

        AjaxResponse("OK: Delete shipping done!");
    }

    #endregion Shipping
    #region RegisSale

    private void DeleteRegisSale()
    {
        string[] stringIDs = GetRequest("regissaleID").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        List<long> longIDs = stringIDs.Select(x => long.Parse(x)).ToList();

        List<Meta> metas = _DR.Meta.WhereIn(t => t.ID, longIDs).ToList();

        foreach (Meta t in metas)
        {
            _DR.DeleteObject(t);
        }        

        _DR.SaveChanges();
        
        metas = null;

        AjaxResponse("OK: Delete shipping done!");
    }
    #endregion RegisSale
    private void SendEmail(string fromEmail, string fromPassword, string fromName, string toEmail, string toName, string subject, string body)
    {
        var fromAddress = new MailAddress(fromEmail, fromName);
        var toAddress = new MailAddress(toEmail, toName);

        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            BodyEncoding = System.Text.Encoding.UTF8,
            IsBodyHtml = true,
            SubjectEncoding = System.Text.Encoding.UTF8,
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        };

        smtp = null;
    }
}